package domain;

import com.mysql.jdbc.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Sandamal
 */
public class DBConnection {
    
    private DBConnection(){
    }
    /**
     * 
     * @return an instance of DBConnection 
     */
    public static DBConnection getDatabaseConn(){
        if(instance==null){
            instance = new DBConnection();
        }
        return instance;
    }
    private static DBConnection instance = null;
    

    private final String host = "jdbc:mysql://localhost:3306/";
    private final String dbName = "expenses";
    private final String userName = "root";
    private final String password = "";
    private final String driver = "com.mysql.jdbc.Driver";
    private Connection con = null;

    /**
     * Connects to the database
     */
    public void connect() {
        try {
            Class.forName(driver).newInstance();
            con = (Connection) DriverManager.getConnection(host + dbName, userName, password);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * Disconnects from the database
     */
    public void disconnect() {
        try {
            con.close();
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
    }

    /**
     * 
     * @param fetchSQL The SQL string to be executed
     * @return Resultset containing the results of the query
     */
    public ResultSet fetch(String fetchSQL) {
        try {
            if (con == null) {
                this.connect();
            }
            Statement st = con.createStatement();
            ResultSet rs = st.executeQuery(fetchSQL);
            return rs;
        } catch (SQLException ex) {
            ex.printStackTrace();
            return null;
        }
    }

    /**
     * 
     * @param updateSQL The SQL string to be executed
     * @return true if the execution is successful
     */
    public boolean  update(String updateSQL) {
        boolean updateStatus = false;
        try {
            if(con == null){
                this.connect();
            }
            Statement st = con.createStatement();
            int updateCount = st.executeUpdate(updateSQL);
            if(updateCount==0){
                updateStatus = false;
            }else{
                updateStatus = true;
            }
            return updateStatus;
                
        } catch (SQLException ex) {
            ex.printStackTrace();
            return false;
        }
    }
}
